package com.dev.base.adapter;

import com.dev.base.ability.MainBean;
import com.dev.base.ability.MainModel;
import dev.base.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.List;
import java.util.Optional;

/**
 * 测试 list adapter
 */
public class NewsListAdapter extends BaseItemProvider {
    private List<MainBean> newsInfoList;
    private Context context;

    public NewsListAdapter(List<MainBean> listBasicInfo, Context context) {
        this.newsInfoList = listBasicInfo;
        this.context = context;
    }

    @Override
    public int getCount() {
        return newsInfoList == null ? 0 : newsInfoList.size();
    }

    @Override
    public Object getItem(int position) {
        return Optional.of(this.newsInfoList.get(position));
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component componentP, ComponentContainer componentContainer) {
        ViewHolder viewHolder = null;
        Component component = componentP;
        if (component == null) {
            component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_news_layout, null, false);
            viewHolder = new ViewHolder();
            viewHolder.image = (Image) component.findComponentById(ResourceTable.Id_item_news_image);
            viewHolder.title=(Text)component.findComponentById(ResourceTable.Id_title);
            viewHolder.content=(Text)component.findComponentById(ResourceTable.Id_content);
            component.setTag(viewHolder);
        } else {
            if (component.getTag() instanceof ViewHolder) {
                viewHolder = (ViewHolder) component.getTag();
            }
        }
        if (null != viewHolder) {
            viewHolder.image.setScaleMode(Image.ScaleMode.STRETCH);
        }
        viewHolder.image.setPixelMap(MainModel.image[position]);
        viewHolder.title.setText("标题"+position);
        viewHolder.content.setText(position+"天前");
        return component;
    }

    /**
     * ViewHolder which has title and image
     */
    private static class ViewHolder {
        Text title;
        Text content;
        Image image;
    }
}
